<?php
namespace App\Common\Cla\Rbac;

use App\Common as com;

class Permission extends com\Cla\ClaBase {

	// ===============================
	//
	//
	// 下面为静态方法
	//
	//
	// ===============================


	/**
	 * 根据权限 id 获取权限 ids
	 * @param string $authSid
	 * @return int 权限id
	 */
	public static function getPermissionIdOfSid( string $authSid ):int {
		$permissionIds = self::getPermissionIdsOfSids( [ $authSid ] );
		if( ! empty( $permissionIds ) ){
			return array_shift( $permissionIds );
		}else{
			return 0;
		}
	}

	/**
	 * 根据权限 ids 获取权限 sids
	 * @param array $authSids
	 * @return array 权限ids
	 */
	public static function getPermissionIdsOfSids( array $authSids ):array {
		// ...
		if( empty( $authSids ) ){
			return [];
		}
		//
		$rbacPermissionManager = com\Model\RbacPermission::dataManager();
		$rbacPermissionManager->newData_Sid()->whereIn( $authSids );
		$permissionIds = $rbacPermissionManager->goModelQuery()->pluck( 'id' )->toArray();
		// 检查
		if( count( $permissionIds ) != count( $authSids ) ){
			throw com\Lib\Err\Exception::makeOfNew( '数据不一致，可能为权限不存在或权限重复，请检查#1', com\Lib\Err\Code::$sysDataError );
		}
		return $permissionIds;
	}

	/**
	 * 根据权限 sids 获取权限ids
	 * @param array $ids
	 * @return array 权限ids
	 */
	public static function getPermissionSidsOfIds( array $ids ):array {
		// ...
		if( empty( $ids ) ){
			return [];
		}
		//
		$rbacPermissionManager = com\Model\RbacPermission::dataManager();
		$rbacPermissionManager->newData_Id()->whereIn( $ids );
		$permissionSids = $rbacPermissionManager->goModelQuery()->pluck( 'sid' )->toArray();
		// 检查
		if( count( $permissionSids ) != count( $ids ) ){
			throw com\Lib\Err\Exception::makeOfNew( '数据不一致，可能为权限不存在或权限重复，请检查#2', com\Lib\Err\Code::$sysDataError );
		}
		return $permissionSids;
	}

	/**
	 * 获取permissionIds以及它的所有上级
	 * @param int $permissionId
	 * @return int[]
	 */
	public static function getPermissionAndAllUpId( int $permissionId ):array {
		return self::getPermissionAndAllUpIds( [ $permissionId ] );
	}

	/**
	 * 获取permissionIds以及它的所有上级
	 * @param array $permissionIds
	 * @return int[]
	 */
	public static function getPermissionAndAllUpIds( array $permissionIds ):array {
		if( empty( $permissionIds ) ){
			return [];
		}
		$rbacPermissionDataUnit = com\Model\RbacPermission::dataUnit();
		$rbacPermissionDataUnit->newData_id()->whereIn( $permissionIds );
		$rbacPermissionDataUnit->newData_ParentId()->whereNotEq( 0 );
		$parentIds = $rbacPermissionDataUnit->goModelQuery()->pluck( 'parent_id' )->toArray();
		//
		if( ! empty( $parentIds ) ){
			$parentIds = array_merge( $parentIds, self::getPermissionAndAllUpIds( $parentIds ) );
		}
		return $parentIds;
	}

}
